import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {
  final String title;
  final VoidCallback? onTap;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final double? width;
  final double height;
  final BorderRadius borderRadius;
  final bool isLoading;
  final String? loadingText;
  final EdgeInsetsGeometry? padding;
  final TextStyle? textStyle;
  final double? elevation;
  final bool isOutlined;

  const CustomButton({
    super.key,
    required this.title,
    this.onTap,
    this.backgroundColor,
    this.foregroundColor,
    this.width,
    this.height = 48,
    this.borderRadius = const BorderRadius.all(Radius.circular(6)),
    this.isLoading = false,
    this.loadingText,
    this.padding,
    this.textStyle,
    this.elevation,
    this.isOutlined = false,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    // 确定按钮颜色
    final bgColor = backgroundColor ?? (isOutlined ? Colors.transparent : colorScheme.primary);
    final fgColor = foregroundColor ?? (isOutlined ? colorScheme.primary : colorScheme.onPrimary);
    final loadingColor = isOutlined ? colorScheme.primary : colorScheme.onPrimary;

    // 构建按钮子内容
    final Widget child =
        isLoading
            ? Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: height - 24,
                  height: height - 24,
                  child: CircularProgressIndicator(strokeWidth: 2, color: loadingColor),
                ),
                if (loadingText != null) ...[
                  const SizedBox(width: 12),
                  Text(loadingText!, style: textStyle ?? theme.textTheme.labelLarge?.copyWith(color: fgColor)),
                ],
              ],
            )
            : Text(title, style: textStyle ?? theme.textTheme.labelLarge?.copyWith(color: fgColor));

    // 构建按钮样式
    final buttonStyle = ElevatedButton.styleFrom(
      backgroundColor: bgColor,
      foregroundColor: fgColor,
      minimumSize: Size(width ?? double.infinity, height),
      padding: padding ?? const EdgeInsets.symmetric(horizontal: 16),
      shape: RoundedRectangleBorder(
        borderRadius: borderRadius,
        side: isOutlined ? BorderSide(color: colorScheme.primary) : BorderSide.none,
      ),
      elevation: elevation ?? (isOutlined ? 0 : 2),
      shadowColor: Colors.transparent,
    );

    return ElevatedButton(onPressed: isLoading ? null : onTap, style: buttonStyle, child: child);
  }
}
